<?php

namespace App\Http\Controllers\Backend;


use App\Models\SiteConfig;
use Illuminate\Support\Facades\DB;
use App\Manage\SiteConfigManage;

class SiteConfigController extends BaseController
{
    // 话题
    public function initialize()
    {
        parent::initialize();
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 配置
    public function setting()
    {
        $options = [];
        $logic   = new SiteConfigManage();
        $list    = $logic->setting($this->myUid, $options);

        return $this->success($list);
    }


    // 获取配置
    public function config()
    {
        $options = [];
        $logic   = new SiteConfigManage();
        $list    = $logic->config($this->myUid, $options);

        return $this->success($list);
    }

    // 获取配置
    public function lists()
    {
        $options = [];
        $logic   = new SiteConfigManage();
        $list    = $logic->lists($this->myUid, $options);

        return $this->success($list);
    }

    // 保存配置
    public function save()
    {
        $options = [];
        $logic   = new SiteConfigManage();
        $res     = $logic->save($this->myUid, $options);
        if($res === false){
            return $this->error($logic->getError());
        }

        return $this->success([], '保存成功！');
    }

    public function save2()
    {
        // 参数
        $data = $this->data;
        $data = $this->filterNull($data);
        $this->throwIf(empty($data), "请传递需要修改的数据！");

        // 获取配置
        $model = new SiteConfig();
        $list  = $model->get()->toArray();
        $list  = array_column($list, null, 'field');
        $table = 'site_config';


        // 保存数据
        DB::beginTransaction();
        try{
            foreach($data as $field => $val){
                $info = $list[$field] ?? [];

                // 添加
                if(empty($info)){
                    // 更新新数据
                    $setArr = ["field" => $field, "cn_value" => $val];
                    $result = DB::table($table)->insert($setArr);
                    if($result === false){
                        throw  new \Exception('保存配置信息失败！！');
                    }
                } else{
                    // 修改
                    $result = DB::table($table)->where(['id' => $info['id']])->update(["cn_value" => $val]);
                    if($result === false){
                        throw  new \Exception('修改原来的配置信息失败！！');
                    }
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();
            $this->throwIf(true, $e->getMessage());
        }

        // 删除缓存
        $model->deleteCacheList($list);

        return $this->success();
    }

}


